<template>
	<div class="license-container flex-container-nomal">
		<div class="license-header">
			<a-space align="center">
				<div class="d-module-title"><b>授权信息</b></div>
				<a-space align="center" class="query-item">
					<span>设备类型：</span>
					<a-select placeholder="请选择设备类型" v-model:value="deviceType" :options="deviceTypeOptions" @change="deviceTypeChange" style="width: 160px" />
				</a-space>
			</a-space>
			<a-space v-action="['mk_contract_tenant_qztx']" align="center" size="large" v-show="showNotice">
				<a-space align="center" v-if="!isDisable">
					<a-switch :checked="reminderChecked" :disabled="isDisable" @change="changeReminder" />
					<span>欠租提醒</span>
				</a-space>
				<a-tooltip placement="bottom" v-if="isDisable">
					<template #title>
						<span>已开启自动欠租提醒，无法手动操作</span>
					</template>
					<a-space align="center">
						<a-switch :checked="reminderChecked" :disabled="isDisable" />
						<span>欠租提醒</span>
					</a-space>
				</a-tooltip>
				<!--        <a-button type="primary" @click="frozen">{{isFrozen?'解冻':'冻结'}}</a-button>-->
			</a-space>
		</div>
		<div class="flex1" style="position: relative">
			<div style="position: absolute; left: 0; right: 0; top: 0; bottom: 0">
				<vxe-table :loading="loading" :data="tableData" stripe align="left" :row-config="{isHover: true, height: 80}" show-overflow height="100%">
					<vxe-column title="状态" min-width="100">
						<template #default="{row}">
							<a-tag v-if="row.type === 'lock'" :color="row?.status?.color">{{ row?.status?.label }}</a-tag>
							<a-tag v-if="row.type === 'access'" :color="statusMap2[row.status]?.color">{{ statusMap2[row.status]?.label }}</a-tag>
						</template>
					</vxe-column>
					<vxe-column title="授权方式" field="from" min-width="90"></vxe-column>
					<vxe-column title="被授权人信息" field="authorizationData" min-width="180">
						<template #default="{row}">{{ row.name || row.realname }}/{{ row.phone }}</template>
					</vxe-column>
					<vxe-column title="授权类型" field="authType" min-width="100"></vxe-column>
					<vxe-column title="授权编号" field="paasId" min-width="100"></vxe-column>
					<vxe-column title="与租户关系" field="relation" min-width="100"></vxe-column>
					<vxe-column title="授权有效期" field="authDate" min-width="190">
						<template #default="{row}">
							<div>{{ row.startTime }} 至</div>
							<div>{{ row.endTime }}</div>
						</template>
					</vxe-column>
					<vxe-column title="欠租提醒" field="backRentRemind" min-width="120"></vxe-column>
					<vxe-column title="备注" field="remark" min-width="100"></vxe-column>
				</vxe-table>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
	import {ref, onMounted, computed, createVNode} from 'vue'
	import {useRequest} from 'vue-request'
	import {getAccessAuthorize, getLockLicense, getLockList} from '@/api/device'
	import {setBackRentRemind, frozenContract, getFrozenState} from '@/api/contract'
	import {message, Modal} from 'ant-design-vue'
	import {ExclamationCircleOutlined} from '@ant-design/icons-vue'
	import {isNBLock} from '@/utils/device'

	const props = defineProps({
		dataSource: {
			type: Object,
			required: true
		}
	})
	const emit = defineEmits(['success'])

	const isNB = ref(false)
	const showNotice = computed(() => {
		return deviceType.value === 'lock' && isNB.value && [24, 25, 27].includes(props.dataSource?.contractStatus)
	})
	const querySnId = async () => {
		const {houseId} = props.dataSource
		const data = {
			deviceType: 5,
			bigType: 3,
			roomId: houseId
		}
		const {
			data: {records}
		} = await getLockList(data)

		isNB.value = records.some((item: any) => {
			return isNBLock(item.sn)
		})
	}

	const statusOptions = [
		{value: 1, label: '不可用', color: 'error'},
		{value: 2, label: '已生效', color: 'success'},
		{value: 3, label: '待生效'},
		{value: 4, label: '已过期', color: 'error'},
		{value: 5, label: '已冻结', color: 'warning'}
	]
	const statusMap = statusOptions.reduce((map: any, status) => {
		map[status.value] = status
		return map
	}, {})

	const statusOptions2 = [
		{value: 0, label: '待生效'},
		{value: 1, label: '已生效', color: 'success'},
		{value: 2, label: '已冻结', color: 'warning'},
		{value: 3, label: '未生效'},
		{value: 4, label: '已过期', color: 'error'}
	]
	const statusMap2 = statusOptions2.reduce((map: any, status: any) => {
		map[status.value] = status
		return map
	}, {})

	const authSourceMap: any = {
		1: '管理员密码',
		2: '合同入住',
		3: '设备',
		4: '同住人申请',
		5: '第三方'
	}
	const authTypeMap: any = {
		1: '密码',
		2: 'IC卡',
		3: '蓝牙',
		4: '指纹'
	}
	const backRentRemindMap: any = {
		0: '关闭',
		1: '开启',
		2: '开启中',
		3: '关闭中'
	}
	const relateRemarkMap: any = {
		1: '父子',
		2: '母子',
		3: '配偶'
	}
	const sceneMap: any = {
		1: '看房',
		2: '入住',
		3: '维修',
		4: '保洁',
		5: '配货',
		6: '其他'
	}
	const operationMap: any = {
		1: '添加',
		2: '删除',
		3: '修改',
		4: '冻结',
		5: '解冻',
		6: '开启欠租提醒',
		7: '关闭欠租提醒'
	}

	const opStatusMap: any = {
		1: '执行中',
		2: '失败',
		3: '成功'
	}

	const deviceType = ref<'lock' | 'access' | ''>('')
	const deviceTypeOptions = [
		{value: '', label: '全部'},
		{value: 'lock', label: '门锁'},
		{value: 'access', label: '门禁'}
	]
	const reminderChecked = ref<boolean>(false)
	const isFrozen = ref<boolean>(false)
	onMounted(() => {
		frozenState()
		deviceTypeChange()
		reminderChecked.value = !!props.dataSource?.backRentRemind
		isFrozen.value = !!props.dataSource?.freezeStatus
		querySnId()
	})

	const tableData = ref<any[]>([])
	const loading = ref<boolean>(false)

	const getLock = async () => {
		const data = {
			relateId: props.dataSource.id,
			size: 9999
		}
		const res = await getLockLicense(data)
		return (res?.data?.records || []).map((data: any) => {
			const {opStatus, operation, remark} = data
			const status = {...statusMap[data.authState]}
			// 不可用并且添加进行中时
			if (data.authState === 1 && operation === 1 && opStatus === 1) {
				status.label = '待同步'
			}
			// 不可用并且添加失败时
			if (data.authState === 1 && operation === 1 && opStatus === 2) {
				status.label = '未生效'
			}
			return {
				...data,
				type: 'lock',
				status,
				from: authSourceMap[data.authSource],
				authType: authTypeMap[data.authType],
				backRentRemind: backRentRemindMap[data.backRentRemindState] || '',
				relation: data.relateRemark || '-',
				reason: sceneMap[data.scene],
				remark: `${operation && opStatus ? `${operationMap[operation]}${opStatusMap[opStatus]}` : remark}`
			}
		})
	}

	async function getAccess() {
		const data = {
			relateId: props.dataSource.id,
			size: 9999
		}
		const res = await getAccessAuthorize(data)
		return (res?.data?.records || []).map((data: any) => {
			return {
				...data,
				type: 'access',
				paasId: '/',
				status: data.status?.value,
				statusLabel: data.status?.label,
				from: authSourceMap[data.authSource],
				authType: data.authType?.label,
				relation: relateRemarkMap[data.relateRemark] || '-',
				reason: sceneMap[data.scene],
				remark: '-',
				startTime: data.authStart,
				endTime: data.authEnd
			}
		})
	}

	async function deviceTypeChange(deviceType?: 'lock' | 'access' | '') {
		loading.value = true
		if (!deviceType) {
			const records1 = await getLock()
			const records2 = await getAccess()
			tableData.value = [...records1, ...records2]
		}
		if (deviceType === 'lock') {
			tableData.value = await getLock()
		}
		if (deviceType === 'access') {
			tableData.value = await getAccess()
		}
		loading.value = false
	}
	//查询欠租提醒是否能修改设置
	const isDisable = ref<boolean>(false)
	const frozenState = () => {
		getFrozenState().then(ref => {
			console.log(ref)
			isDisable.value = ref.data
		})
	}
	async function changeReminder(value: boolean) {
		if (value) {
			const data = {
				id: props.dataSource.id,
				onOff: 1
			}
			await setBackRentRemind(data)
			reminderChecked.value = value
			message.success('操作成功')
			emit('success')
		} else {
			Modal.confirm({
				title: '关闭欠租提醒',
				centered: true,
				icon: createVNode(ExclamationCircleOutlined),
				content: `关闭欠租提醒后，${props.dataSource?.renterInfo?.name || ''}相关授权开门时将不会播报欠租提醒`,
				async onOk() {
					const data = {
						id: props.dataSource.id,
						onOff: 0
					}
					await setBackRentRemind(data)
					reminderChecked.value = value
					message.success('操作成功')
					emit('success')
					deviceTypeChange(deviceType.value)
				}
			})
		}
	}

	async function frozen() {
		const data = {
			id: props.dataSource.id,
			frozen: isFrozen.value ? 0 : 1
		}
		await frozenContract(data)
		message.success('操作成功')
		isFrozen.value = !isFrozen.value
	}
</script>

<style scoped>
	.license-container {
		height: 100%;
	}

	.license-container .d-module-title {
		margin: 0;
	}

	.query-item {
		margin-left: 24px;
	}

	.license-header {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		padding-bottom: 12px;
	}

	.table-box {
		flex: 1;
		overflow: hidden;
	}
</style>
